package com.shanghaionstar.activity.webview.handler;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;

import com.onstar.cn.ShareEntity;
import com.onstar.cn.common.jsBridge.BridgeHandler;
import com.onstar.cn.common.jsBridge.BridgeWebView;
import com.onstar.cn.common.jsBridge.CallBackFunction;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.smart.BaseResponse;
import com.onstar.cn.smart.entity.ServiceItem;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.nav.share.ShareDialog;
import com.shanghaionstar.user.iview.IOptViewImpl;
import com.shanghaionstar.user.presenter.OptPresenter;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.weight.CarAssessSecAgreementDialog;
import com.shanghaionstar.weight.TopLayout;

import java.util.List;

/**
 * Created by Rengui Lu on 2017/3/3.
 */
public class CommonWebShareHelper {
    private ShareEntity shareContentEntity = null;
    private String shareUrl;
    private Context context;

    public CommonWebShareHelper(Context context) {
        this.context = context;
    }


    /***********************
     * 分享报告协议分界线
     *********************/
    ProgressDialog progressDialog;

    private void showProgress() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(context);
            progressDialog.setMessage(context.getString(com.onstar.cn.framework.R.string.waiting));
        }
        progressDialog.show();
    }

    private void hideProgress() {
        if (progressDialog != null)
            progressDialog.dismiss();
    }


    public void registerHandler(final TopLayout topLayout, BridgeWebView webView) {
        webView.registerHandler("getShareUrl", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (!CommonUtil.isNull(data)) {
                    shareContentEntity = GsonHelper.fromJson(data, ShareEntity.class);
                    showShare(shareContentEntity.getShareUrl(), topLayout);
                }
                topLayout.showRightButton(!CommonUtil.isNull(data));
            }
        });
    }


    /**
     * 评价服务presenter
     */
    private OptPresenter optPresenter;

    public OptPresenter getOptPresenter() {
        if (optPresenter == null && context instanceof BaseActivity) {
            optPresenter = new OptPresenter(((BaseActivity) context).getScheduler(), context);
            optPresenter.setOptView(new IOptViewImpl() {
                @Override
                public void onTurnOnCarAssessSuccess(BaseResponse response) {
                    hideProgress();
                    showShareDialog(shareUrl);
                }

                @Override
                public void onTurnOffCarAssessSuccess(BaseResponse response) {
                    hideProgress();
                }

                @Override
                public void onTurnCarAssessFailed(Throwable throwable) {
                    hideProgress();
                    if (throwable != null && !TextUtils.isEmpty(throwable.getMessage())) {
                        new ToastView(context).showToast(throwable.getMessage());
                    }
                }

                @Override
                public void showCarAssessAgreement(Boolean show) {
                    hideProgress();
                    ServiceItem item = optPresenter.getServiceItemByName(OptPresenter.CAR_ASSESSMENT);
                    if (show && ServiceItem.isCarAssessClosed(item))
                        showCarAssessAgreeDialog();
                }

                @Override
                public void onSwitchService(String name, boolean in, boolean isSuc, Throwable throwable) {
                    super.onSwitchService(name, in, isSuc, throwable);
                    ServiceItem item = getOptPresenter().getServiceItemByName(name);
                    if (isSuc)
                        item.setOptStatus(in ? "1" : "0");
                    if (isSuc) {
                        if (in) {
                            onTurnOffCarAssessSuccess(null);
                        } else {
                            onTurnOffCarAssessSuccess(null);
                        }
                    } else {
                        onTurnCarAssessFailed(throwable);
                    }
                }

                @Override
                public void onGetServiceItem(List<ServiceItem> item) {
                    super.onGetServiceItem(item);
                    if (item == null) {
                        showCarAssessAgreement(false);
                    } else {
                        ServiceItem carAssessmentItem = optPresenter.getServiceItemByName(OptPresenter.CAR_ASSESSMENT);
                        if (ServiceItem.isCarAssessAvailable(carAssessmentItem)) {
                            String loginRole = ApplicationUtil.getInstance().getLoginRole();
                            boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
                            if (context != null && isOwner)
                                showCarAssessAgreement(true);
                        } else {
                            if (context != null)
                                showCarAssessAgreement(false);
                        }
                    }
                }
            });
        }
        return optPresenter;
    }

    /**
     * 车况检测报告分析协议对话框
     */
    CarAssessSecAgreementDialog carAssessDialog;

    private void showCarAssessAgreeDialog() {
        if (carAssessDialog == null) {
            carAssessDialog = new CarAssessSecAgreementDialog(context);
            carAssessDialog.setCarAssessmentAgreeListener(new CarAssessSecAgreementDialog.carAssessmentAgreeListener() {
                @Override
                public void doOnAgree() {
                    showProgress();
                    carAssessDialog.dismiss();
                    getOptPresenter().optIn(OptPresenter.CAR_ASSESSMENT);
                    BusinessUtil.sendReportByClickType(context, FunctionNameFindId.DiagShare_AgreeProtocolShareReport.getStringValue());//车况检测报告点击分享_同意协议分享报告
                }
            });
        }
        if (context instanceof BaseActivity && !((BaseActivity) context).isFinishing())
            carAssessDialog.show();
    }

    private void showShareDialog(String shareUrl) {
        BusinessUtil.sendReportByClickType(context, FunctionNameFindId.DiagnosticsShare.getStringValue());
        ShareDialog dialog = new ShareDialog(context, R.style.Theme_Transparent);
        dialog.setShareUrl(shareUrl);
        dialog.setShareTitle(shareContentEntity.getShareTitle());
        dialog.setShareDescription(shareContentEntity.getShareMsg());
        dialog.setShareImageUrl(shareContentEntity.getShareImg());
        dialog.setReportCancel(FunctionNameFindId.DiagShare_Cancel.getStringValue());
        dialog.setMoments(FunctionNameFindId.DiagShare_Moments.getStringValue());
        dialog.setWechat(FunctionNameFindId.DiagShare_Wechat.getStringValue());
        dialog.show();
    }

    public void showShare(final String shareUrl, final TopLayout topLayout) {
        this.shareUrl = shareUrl;
        ((BaseActivity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                topLayout.setOnRightTextClickLstener(context.getString(R.string.share), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (context.getString(R.string.driver_assessment_title).equalsIgnoreCase(topLayout.getTitle())) {
                            ServiceItem item = getOptPresenter().getServiceItemByName(OptPresenter.CAR_ASSESSMENT);
                            if (item == null) {
                                showProgress();
                                getOptPresenter().getServiceStatus(context);
                            } else if (ServiceItem.isCarAssessOpen(item)) { //已经同意分享协议了则显示分享栏
                                String loginRole = ApplicationUtil.getInstance().getLoginRole();
                                boolean isOwner = !CommonUtil.isNull(loginRole) && loginRole.equalsIgnoreCase(JoinMeConstants.OWNER);
                                if (isOwner)
                                    showShareDialog(shareUrl);
                            } else if (ServiceItem.isCarAssessInDeveloping(item)) {
                                ToastUtil.show(context, context.getString(R.string.in_developing_notification));
                            } else if (ServiceItem.isCarAssessClosed(item)) {
                                showCarAssessAgreeDialog();
                            }
                        } else {
                            showShareDialog(shareUrl);
                        }
                    }
                });
            }

        });
    }


}



